<script setup>
import dayjs from 'dayjs'
import { reactive, ref, watch } from 'vue'

import { fetchAlertDeviceData } from '@/api/manager/dataManage/deviceManage.js'

defineOptions({
  name: 'AlertDeviceData',
})

const props = defineProps({
  pkid: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['close'])

const dialogVisible = ref(false)

const total = ref(0)

const searchParams = reactive({
  pageIndex: 1,
  pageSize: 10,
})

const deviceData = ref([])

const fetchDeviceData = () => {
  fetchAlertDeviceData({
    ...searchParams,
    deviceId: props.pkid,
  }).then((res) => {
    total.value = res.count
    deviceData.value = res.list
  })
}

const handleSizeChange = (size) => {
  searchParams.pageIndex = 1
  searchParams.pageSize = size
  fetchDeviceData()
}

const handlePageChange = (page) => {
  searchParams.pageIndex = page
  fetchDeviceData()
}

const afterOpened = () => {
  fetchDeviceData()
}

const handleClose = () => {
  dialogVisible.value = false
}

watch(dialogVisible, (val) => {
  if (!val) {
    searchParams.pageIndex = 1
    searchParams.pageSize = 10
    deviceData.value = []
  }
})

defineExpose({ dialogVisible })
</script>

<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    title="设备数据"
    width="800px"
    @close="handleClose"
    @opened="afterOpened"
  >
    <div class="device-data-content">
      <el-table
        class="custom-table"
        :data="deviceData"
        show-overflow-tooltip
        :tooltip-options="{ showAfter: 300 }"
      >
        <el-table-column type="index" label="序号" width="60px" />
        <el-table-column prop="content" label="报警内容" />
        <el-table-column fixed="right" label="报警时间" width="160px">
          <template #default="scope">
            {{ dayjs(scope.row.timestamp).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="custom-pagination"
        :current-page="searchParams.pageIndex"
        :page-size="searchParams.pageSize"
        background
        :page-sizes="[10, 20, 30, 50]"
        layout="total, prev, pager, next, sizes, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.device-data-content {
  height: 500px;
  display: flex;
  flex-direction: column;
  padding: 0;

  .el-table {
    flex: 1;
  }

  .el-pagination {
    margin-top: 16px;
    align-self: flex-end;
  }
}
</style>
